<script lang="ts">
  import type { Folder, Editor } from "$lib/ebm";
  import { actixGraphqlEndpoint, activeFolderId } from "$lib/js/stores";
  import { request, gql } from "graphql-request";

  import { tooltip } from "$lib/js/tooltip";
  import { useMutation, useQueryClient } from "@sveltestack/svelte-query";

  export let expanded = false;
  export let folder: Folder;

  const queryClient = useQueryClient();

  let endpoint = $actixGraphqlEndpoint;
  const openEditorMutation = useMutation<
    Editor,
    { message: string },
    {
      id_: string;
      title_: string;
    }
  >(
    async ({ id_, title_ }) => {
      const { editor } = await request(
        endpoint,
        gql`
          mutation ($id: ID!, $title: String!) {
            editor: openEditor(input: { id: $id, title: $title }) {
              id
              snapshotAt
              title
              createdAt
              updatedAt
              status
              from
            }
          }
        `,
        {
          id: id_,
          title: title_,
        }
      );
      return editor;
    },
    {
      onSuccess: () => {
        queryClient.invalidateQueries("editors_query");
      },
    }
  );

  function openEditor() {
    $openEditorMutation.mutate({
      id_: folder.id,
      title_: folder.folderName,
    });
    console.log(
      "double click to open editor for folder={}, id={}",
      folder.folderName,
      folder.id
    );
  }

  const handleFolderClick = (id) => () => {
    expanded = !expanded;
    $activeFolderId = id;
  };
</script>

<div class="w-full">
  <span
    class="hover:bg-green-50 truncate w-full pl-5"
    class:expanded
    on:click={handleFolderClick(folder.id)}
    on:dblclick={openEditor}
  >
    {folder.folderName}
  </span>

  {#if expanded}
    <ul class="w-full flex-1 flex-col">
      {#if folder.folders}
        {#each folder.folders as folder}
          <li class="w-full">
            <svelte:self {folder} expand={false} />
          </li>
        {/each}
      {/if}
    </ul>
  {/if}
</div>

<style>
  span {
    background: url(icons/folder.svg) 0 0.1em no-repeat;
    background-size: 1em 1em;
    font-weight: bold;
    cursor: pointer;
  }

  .expanded {
    background-image: url(icons/folder-open.svg);
  }

  ul {
    padding: 0.2em 0 0 0.5em;
    margin: 0 0 0 0.5em;
    list-style: none;
    border-left: 1px solid #eee;
  }

  li {
    padding: 0.2em 0;
  }
</style>
